home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 December / PCWorld_2007-12_cd.bin / v cisle / htttrack / httrack-3.41-3.exe / {app} / src / htscache.c < prev    next >
C/C++ Source or Header  |  2007-02-06  |  68KB  |  1,792 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: httrack.c subroutines:                                 */
  34. /*       cache system (index and stores files in cache)         */
  35. /* Author: Xavier Roche                                         */
  36. /* ------------------------------------------------------------ */
  37.  
  38. /* Internal engine bytecode */
  39. #define HTS_INTERNAL_BYTECODE
  40.  
  41. #include "htscache.h"
  42.  
  43. /* specific definitions */
  44. #include "htscore.h"
  45. #include "htsbasenet.h"
  46. #include "htsmd5.h"
  47. #include <time.h>
  48.  
  49. #include "htszlib.h"
  50. /* END specific definitions */
  51.  
  52. #undef test_flush
  53. #define test_flush if (opt->flush) { fflush(opt->log); fflush(opt->log); }
  54.  
  55. // routines de mise en cache
  56.  
  57. /*
  58.   VERSION 1.0 :
  59.   -----------
  60.  
  61. .ndx file
  62.  file with data
  63.    <string>(date/time) [ <string>(hostname+filename) (datfile_position_ascii) ] * number_of_links
  64.  file without data
  65.    <string>(date/time) [ <string>(hostname+filename) (-datfile_position_ascii) ] * number_of_links
  66.  
  67. .dat file
  68.  [ file ] * 
  69. with
  70.   file= (with data)
  71.    [ bytes ] * sizeof(htsblk header) [ bytes ] * n(length of file given in htsblk header)
  72.  file= (without data)
  73.    [ bytes ] * sizeof(htsblk header)
  74. with
  75.  <string>(name) = <length in ascii>+<lf>+<data>
  76.  
  77.  
  78.   VERSION 1.1/1.2 :
  79.   ---------------
  80.  
  81. .ndx file
  82.  file with data
  83.    <string>("CACHE-1.1") <string>(date/time) [ <string>(hostname+filename) (datfile_position_ascii) ] * number_of_links
  84.  file without data
  85.    <string>("CACHE-1.1") <string>(date/time) [ <string>(hostname+filename) (-datfile_position_ascii) ] * number_of_links
  86.  
  87. .dat file
  88.    <string>("CACHE-1.1") [ [Header_1.1] [bytes] * n(length of file given in header) ] *
  89. with
  90.  Header_1.1=
  91.    <int>(statuscode)
  92.    <int>(size)
  93.    <string>(msg)
  94.    <string>(contenttype)
  95.    <string>(charset) [version 3]
  96.    <string>(last-modified)
  97.    <string>(Etag)
  98.    <string>location
  99.    <string>Content-disposition [version 2]
  100.    <string>hostname [version 4]
  101.    <string>URI filename [version 4]
  102.    <string>local filename [version 4]
  103.    [<string>"SD" <string>(supplemental data)]
  104.    [<string>"SD" <string>(supplemental data)]
  105.    ...
  106.    <string>"HTS" (end of header)
  107.    <int>(number of bytes of data) (0 if no data written)
  108. */
  109.  
  110. // Nouveau: si != text/html ne stocke que la taille
  111.  
  112.  
  113. void cache_mayadd(httrackp* opt,cache_back* cache,htsblk* r,const char* url_adr,const char* url_fil,const char* url_save) {
  114.   if ((opt->debug>0) && (opt->log!=NULL)) {
  115.     HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"File checked by cache: %s"LF,url_adr);
  116.   }            
  117.   // ---stockage en cache---
  118.   // stocker dans le cache?
  119.   if (opt->cache) {
  120.     if (cache_writable(cache)) {
  121.       // ensure not a temporary filename (should not happend ?!)
  122.       if (IS_DELAYED_EXT(url_save)) {
  123.         if (opt->log!=NULL) {
  124.           HTS_LOG(opt,LOG_WARNING); fprintf(opt->log, "aborted cache validation: %s%s still has temporary name %s"LF, url_adr, url_fil, url_save);
  125.         }
  126.         return ;
  127.       }
  128.  
  129.       // c'est le seul endroit ou l'on ajoute des elements dans le cache (fichier entier ou header)
  130.       // on stocke tout fichier "ok", mais Θgalement les rΘponses 404,301,302...
  131.       if (
  132. #if 1
  133.         r->statuscode > 0
  134. #else
  135.         /* We don't store 5XX errors, because it might be a server problem */
  136.         (r->statuscode==HTTP_OK)        /* stocker rΘponse standard, plus */
  137.         || (r->statuscode==204)     /* no content */
  138.         || HTTP_IS_REDIRECT(r->statuscode)    /* redirect */
  139.         || (r->statuscode==401)     /* authorization */
  140.         || (r->statuscode==403)     /* unauthorized */
  141.         || (r->statuscode==404)     /* not found */
  142.         || (r->statuscode==410)     /* gone */
  143. #endif
  144.         )
  145.       {        /* ne pas stocker si la page gΘnΘrΘe est une erreur */
  146.         if (!r->is_file) {
  147.           // stocker fichiers (et robots.txt)
  148.           if ( url_save == NULL || (strnotempty(url_save)) || (strcmp(url_fil,"/robots.txt")==0)) {
  149.             // ajouter le fichier au cache
  150.                         cache_add(opt,cache,r,url_adr,url_fil,url_save,opt->all_in_cache,StringBuff(opt->path_html));
  151.             //
  152.             // store a reference NOT to redo the same test zillions of times!
  153.             // (problem reported by Lars Clausen)
  154.             // we just store statuscode + location (if any)
  155.             if (url_save == NULL && r->statuscode / 100 >= 3) {
  156.               // cached "fast" header doesn't uet exists
  157.               if (inthash_read(cache->cached_tests, concat(OPT_GET_BUFF(opt), url_adr, url_fil), NULL) == 0) {
  158.                 char BIGSTK tempo[HTS_URLMAXSIZE*2];
  159.                 sprintf(tempo, "%d", (int)r->statuscode);
  160.                 if (r->location != NULL && r->location[0] != '\0') {
  161.                   strcatbuff(tempo, "\n");
  162.                   strcatbuff(tempo, r->location);
  163.                 }
  164.                 if ((opt->debug>0) && (opt->log!=NULL)) {
  165.                   HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log, "Cached fast-header response: %s%s is %d"LF, url_adr, url_fil, (int)r->statuscode);
  166.                 }
  167.                 inthash_add(cache->cached_tests, concat(OPT_GET_BUFF(opt), url_adr, url_fil), (intptr_t)strdupt(tempo));
  168.               }
  169.             }
  170.           }
  171.         }
  172.       }
  173.     }
  174.   }
  175.   // ---fin stockage en cache---
  176. }
  177.  
  178. #if 1
  179.  
  180. #define ZIP_FIELD_STRING(headers, headersSize, field, value) do { \
  181.   if ( (value != NULL) && (value)[0] != '\0') { \
  182.     sprintf(headers + headersSize, "%s: %s\r\n", field, (value != NULL) ? (value) : ""); \
  183.     (headersSize) += (int) strlen(headers + headersSize); \
  184.   } \
  185. } while(0)
  186. #define ZIP_FIELD_INT(headers, headersSize, field, value) do { \
  187.   if ( (value != 0) ) { \
  188.     sprintf(headers + headersSize, "%s: "LLintP"\r\n", field, (LLint)(value)); \
  189.     (headersSize) += (int) strlen(headers + headersSize); \
  190.   } \
  191. } while(0)
  192. #define ZIP_FIELD_INT_FORCE(headers, headersSize, field, value) do { \
  193.   sprintf(headers + headersSize, "%s: "LLintP"\r\n", field, (LLint)(value)); \
  194.   (headersSize) += (int) strlen(headers + headersSize); \
  195. } while(0)
  196.  
  197. struct cache_back_zip_entry {
  198.   unsigned long int hdrPos;
  199.   unsigned long int size;
  200.   int compressionMethod;
  201. };
  202.  
  203. #define ZIP_READFIELD_STRING(line, value, refline, refvalue) do { \
  204.   if (line[0] != '\0' && strfield2(line, refline)) { \
  205.     strcpybuff(refvalue, value); \
  206.     line[0] = '\0'; \
  207.     } \
  208. } while(0)
  209. #define ZIP_READFIELD_INT(line, value, refline, refvalue) do { \
  210.   if (line[0] != '\0' && strfield2(line, refline)) { \
  211.     int intval = 0; \
  212.     sscanf(value, "%d", &intval); \
  213.     (refvalue) = intval; \
  214.     line[0] = '\0'; \
  215.     } \
  216. } while(0)
  217.  
  218.  
  219. /* Ajout d'un fichier en cache */
  220. void cache_add(httrackp* opt,cache_back* cache,const htsblk *r,const char* url_adr,const char* url_fil,const char* url_save,int all_in_cache,const char* path_prefix) {
  221.   char BIGSTK filename[HTS_URLMAXSIZE*4];
  222.     char catbuff[CATBUFF_SIZE];
  223.   int dataincache=0;    // put data in cache ?
  224.   char BIGSTK headers[8192];
  225.   int headersSize = 0;
  226.   int entryBodySize = 0;
  227.   int entryFilenameSize = 0;
  228.   zip_fileinfo fi;
  229.     const char* url_save_suffix = url_save;
  230.     int zErr;
  231.  
  232.   // robots.txt hack
  233.   if (url_save == NULL) {
  234.     dataincache=0;        // testing links
  235.   }
  236.   else {
  237.     if ( (strnotempty(url_save)==0) ) {
  238.       if (strcmp(url_fil,"/robots.txt")==0)        // robots.txt
  239.         dataincache=1;
  240.       else
  241.         return;   // error (except robots.txt)
  242.     }
  243.  
  244.     /* Data in cache ? */
  245.     if (is_hypertext_mime(opt,r->contenttype, url_fil)
  246.             || (may_be_hypertext_mime(opt,r->contenttype, url_fil) && r->adr != NULL)
  247.             )
  248.         {
  249.       dataincache=1;
  250.         } else if (all_in_cache) {
  251.       dataincache=1;
  252.         }
  253.   }
  254.  
  255.   if (r->size < 0)   // error
  256.     return;
  257.  
  258.   // data in cache
  259.   if (dataincache) {
  260.     assertf(((int) r->size) == r->size);
  261.     entryBodySize = (int) r->size;
  262.   }
  263.  
  264.   /* Fields */
  265.   headers[0] = '\0';
  266.   headersSize = 0;
  267.   /* */
  268.   {
  269.     const char* message;
  270.     if (strlen(r->msg) < 32) {
  271.       message = r->msg;
  272.     } else {
  273.       message = "(See X-StatusMessage)";
  274.     }
  275.     /* 64 characters MAX for first line */
  276.     sprintf(headers + headersSize, "HTTP/1.%c %d %s\r\n", '1', r->statuscode, r->msg);
  277.   }
  278.   headersSize += (int) strlen(headers + headersSize);
  279.  
  280.     if (path_prefix != NULL && path_prefix[0] != '\0' && url_save != NULL && url_save[0] != '\0') {
  281.         int prefixLen = (int) strlen(path_prefix);
  282.         if (strncmp(url_save, path_prefix, prefixLen) == 0) {
  283.             url_save_suffix += prefixLen;
  284.         }
  285.     }
  286.  
  287.   /* Second line MUST ALWAYS be X-In-Cache */
  288.   ZIP_FIELD_INT_FORCE(headers, headersSize, "X-In-Cache", dataincache);
  289.   ZIP_FIELD_INT(headers, headersSize, "X-StatusCode", r->statuscode);
  290.   ZIP_FIELD_STRING(headers, headersSize, "X-StatusMessage", r->msg);
  291.   ZIP_FIELD_INT(headers, headersSize, "X-Size", r->size);           // size
  292.   ZIP_FIELD_STRING(headers, headersSize, "Content-Type", r->contenttype);      // contenttype
  293.   ZIP_FIELD_STRING(headers, headersSize, "X-Charset", r->charset);          // contenttype
  294.   ZIP_FIELD_STRING(headers, headersSize, "Last-Modified", r->lastmodified);     // last-modified
  295.   ZIP_FIELD_STRING(headers, headersSize, "Etag", r->etag);             // Etag
  296.   ZIP_FIELD_STRING(headers, headersSize, "Location", r->location);         // 'location' pour moved
  297.   ZIP_FIELD_STRING(headers, headersSize, "Content-Disposition", r->cdispo);           // Content-disposition
  298.   ZIP_FIELD_STRING(headers, headersSize, "X-Addr", url_adr);            // Original address
  299.   ZIP_FIELD_STRING(headers, headersSize, "X-Fil", url_fil);            // Original URI filename
  300.   ZIP_FIELD_STRING(headers, headersSize, "X-Save", url_save_suffix);           // Original save filename
  301.   
  302.   entryFilenameSize = (int) ( strlen(url_adr) + strlen(url_fil));
  303.   
  304.   /* Filename */
  305.   if (!link_has_authority(url_adr)) {
  306.     strcpybuff(filename, "http://");
  307.   } else {
  308.     strcpybuff(filename, "");
  309.   }
  310.   strcatbuff(filename, url_adr);
  311.   strcatbuff(filename, url_fil);
  312.  
  313.   /* Time */
  314.   memset(&fi, 0, sizeof(fi));
  315.   if (r->lastmodified[0] != '\0') {
  316.         struct tm buffer;
  317.     struct tm* tm_s=convert_time_rfc822(&buffer, r->lastmodified);
  318.     if (tm_s) {
  319.       fi.tmz_date.tm_sec = (uInt) tm_s->tm_sec;
  320.       fi.tmz_date.tm_min = (uInt) tm_s->tm_min;
  321.       fi.tmz_date.tm_hour = (uInt) tm_s->tm_hour;
  322.       fi.tmz_date.tm_mday = (uInt) tm_s->tm_mday;
  323.       fi.tmz_date.tm_mon = (uInt) tm_s->tm_mon;
  324.       fi.tmz_date.tm_year = (uInt) tm_s->tm_year;
  325.     }
  326.   }
  327.   
  328.   /* Open file - NOTE: headers in "comment" */
  329.   if ((zErr = zipOpenNewFileInZip((zipFile) cache->zipOutput,
  330.     filename,
  331.     &fi,
  332.     /* 
  333.     Store headers in realtime in the local file directory as extra field
  334.     In case of crash, we'll be able to recover the whole ZIP file by rescanning it
  335.     */
  336.     headers,
  337.     (uInt) strlen(headers),
  338.     NULL,
  339.     0,
  340.     NULL, /* comment */
  341.     Z_DEFLATED,
  342.     Z_DEFAULT_COMPRESSION)) != Z_OK)
  343.   {
  344.     int zip_zipOpenNewFileInZip_failed = 0;
  345.     assertf(zip_zipOpenNewFileInZip_failed);
  346.   }
  347.   
  348.   /* Write data in cache */
  349.   if (dataincache) {
  350.     if (r->is_write == 0) {
  351.       if (r->size > 0 && r->adr != NULL) {
  352.         if ((zErr = zipWriteInFileInZip((zipFile) cache->zipOutput, r->adr, (int) r->size)) != Z_OK) {
  353.           int zip_zipWriteInFileInZip_failed = 0;
  354.           assertf(zip_zipWriteInFileInZip_failed);
  355.         }
  356.       }
  357.     } else {
  358.       FILE* fp;
  359.       // On recopie le fichier->.
  360.       off_t file_size=fsize(fconv(catbuff, url_save));
  361.       if (file_size>=0) {
  362.         fp=fopen(fconv(catbuff, url_save),"rb");
  363.         if (fp!=NULL) {
  364.           char BIGSTK buff[32768];
  365.           size_t nl;
  366.           do {
  367.             nl=fread(buff,1,32768,fp);
  368.             if (nl>0) { 
  369.               if ((zErr = zipWriteInFileInZip((zipFile) cache->zipOutput, buff, (int) nl)) != Z_OK) {
  370.                 int zip_zipWriteInFileInZip_failed = 0;
  371.                 assertf(zip_zipWriteInFileInZip_failed);
  372.               }
  373.             }
  374.           } while(nl>0);
  375.           fclose(fp);
  376.         } else {
  377.           /* Err FIXME - lost file */
  378.         }
  379.       } /* Empty files are OK */
  380.     }
  381.   }
  382.   
  383.   /* Close */
  384.   if ((zErr = zipCloseFileInZip((zipFile) cache->zipOutput)) != Z_OK) {
  385.     int zip_zipCloseFileInZip_failed = 0;
  386.     assertf(zip_zipCloseFileInZip_failed);
  387.   }
  388.  
  389.   /* Flush */
  390.   if ((zErr = zipFlush((zipFile) cache->zipOutput)) != 0) {
  391.     int zip_zipFlush_failed = 0;
  392.     assertf(zip_zipFlush_failed);
  393.   }
  394. }
  395.  
  396. #else
  397.  
  398. /* Ajout d'un fichier en cache */
  399. void cache_add(httrackp* opt,cache_back* cache,const htsblk *r,char* url_adr,char* url_fil,char* url_save,int all_in_cache) {
  400.   int pos;
  401.   char s[256];
  402.   char BIGSTK buff[HTS_URLMAXSIZE*4];
  403.   int ok=1;
  404.   int dataincache=0;    // donnΘe en cache?
  405.   FILE* cache_ndx = cache->ndx;
  406.   FILE* cache_dat = cache->dat;
  407.   /*char digest[32+2];*/
  408.   /*digest[0]='\0';*/
  409.  
  410.   // Longueur url_save==0?
  411.   if ( (strnotempty(url_save)==0) ) {
  412.     if (strcmp(url_fil,"/robots.txt")==0)        // robots.txt
  413.       dataincache=1;
  414.     else if (strcmp(url_fil,"/test")==0)        // testing links
  415.       dataincache=0;
  416.     else
  417.       return;   // erreur (sauf robots.txt)
  418.   }
  419.  
  420.   if (r->size <= 0)   // taille <= 0 
  421.     return;          // refusΘ..
  422.  
  423.   // Mettre les *donΘes* en cache ?
  424.   if (is_hypertext_mime(opt,r->contenttype, url_fil))    // html, mise en cache des donnΘes et 
  425.     dataincache=1;                               // pas uniquement de l'en tΩte
  426.   else if (all_in_cache)
  427.     dataincache=1;                               // forcer tout en cache
  428.  
  429.   /* calcul md5 ? */
  430.   /*
  431.   if (is_hypertext_mime(opt,r->contenttype)) {    // html, calcul MD5
  432.     if (r->adr) {
  433.       domd5mem(r->adr,r->size,digest,1);
  434.     }
  435.   }*/
  436.  
  437.   // Position
  438.   fflush(cache_dat); fflush(cache_ndx);
  439.   pos=ftell(cache_dat);
  440.   // Θcrire pointeur seek, adresse, fichier
  441.   if (dataincache)   // patcher
  442.     sprintf(s,"%d\n",pos);    // ecrire tel que (eh oui Θvite les \0..)
  443.   else
  444.     sprintf(s,"%d\n",-pos);   // ecrire tel que (eh oui Θvite les \0..)
  445.  
  446.   // data
  447.   // Θcrire donnΘes en-tΩte, donnΘes fichier
  448.   /*if (!dataincache) {   // patcher
  449.     r->size=-r->size;  // nΘgatif
  450.   }*/
  451.  
  452.   // Construction header
  453.   ok=0;
  454.   if (cache_wint(cache_dat,r->statuscode) != -1       // statuscode
  455.   && cache_wLLint(cache_dat,r->size) != -1           // size
  456.   && cache_wstr(cache_dat,r->msg) != -1              // msg
  457.   && cache_wstr(cache_dat,r->contenttype) != -1      // contenttype
  458.   && cache_wstr(cache_dat,r->charset) != -1          // contenttype
  459.   && cache_wstr(cache_dat,r->lastmodified) != -1     // last-modified
  460.   && cache_wstr(cache_dat,r->etag) != -1             // Etag
  461.   && cache_wstr(cache_dat,(r->location!=NULL)?r->location:"") != -1         // 'location' pour moved
  462.   && cache_wstr(cache_dat,r->cdispo) != -1           // Content-disposition
  463.   && cache_wstr(cache_dat,url_adr) != -1            // Original address
  464.   && cache_wstr(cache_dat,url_fil) != -1            // Original URI filename
  465.   && cache_wstr(cache_dat,url_save) != -1           // Original save filename
  466.   && cache_wstr(cache_dat,r->headers) != -1          // Full HTTP Headers
  467.   && cache_wstr(cache_dat,"HTS") != -1              // end of header
  468.   ) {
  469.     ok=1;       /* ok */
  470.   }
  471.   // Fin construction header
  472.  
  473.   /*if ((int) fwrite((char*) &r,1,sizeof(htsblk),cache_dat) == sizeof(htsblk)) {*/
  474.   if (ok) {
  475.     if (dataincache) {    // mise en cache?
  476.       if (!r->adr) {       /* taille nulle (parfois en cas de 301 */
  477.         if (cache_wLLint(cache_dat,0)==-1)          /* 0 bytes */
  478.           ok=0;
  479.       } else if (r->is_write==0) {  // en mΘmoire, recopie directe
  480.         if (cache_wLLint(cache_dat,r->size)!=-1) {
  481.           if (r->size>0) {   // taille>0
  482.             if (fwrite(r->adr,1,r->size,cache_dat)!=r->size)
  483.               ok=0;
  484.           } else    // taille=0, ne rien Θcrire
  485.             ok=0;
  486.         } else
  487.           ok=0;
  488.       } else {  // recopier fichier dans cache
  489.         FILE* fp;
  490.         // On recopie le fichier->.
  491.         off_t file_size=fsize(fconv(catbuff, url_save));
  492.         if (file_size>=0) {
  493.           if (cache_wLLint(cache_dat,file_size)!=-1) {
  494.             fp=fopen(fconv(catbuff, url_save),"rb");
  495.             if (fp!=NULL) {
  496.               char BIGSTK buff[32768];
  497.               ssize_t nl;
  498.               do {
  499.                 nl=fread(buff,1,32768,fp);
  500.                 if (nl>0) { 
  501.                   if (fwrite(buff,1,nl,cache_dat)!=nl) {  // erreur
  502.                     nl=-1;
  503.                     ok=0;
  504.                   }
  505.                 }
  506.               } while(nl>0);
  507.               fclose(fp);
  508.             } else ok=0;
  509.           } else ok=0;
  510.         } else ok=0;
  511.       }
  512.     } else {
  513.       if (cache_wLLint(cache_dat,0)==-1)          /* 0 bytes */
  514.         ok=0;
  515.     }
  516.   } else ok=0;
  517.   /*if (!dataincache) {   // dΘpatcher
  518.     r->size=-r->size;
  519.   }*/
  520.  
  521.   // index
  522.   // adresse+cr+fichier+cr
  523.   if (ok) {
  524.     buff[0]='\0'; strcatbuff(buff,url_adr); strcatbuff(buff,"\n"); strcatbuff(buff,url_fil); strcatbuff(buff,"\n");
  525.     cache_wstr(cache_ndx,buff);
  526.     fwrite(s,1,strlen(s),cache_ndx);
  527.   }  // si ok=0 on a peut Ωtre Θcrit des donnΘes pour rien mais on s'en tape
  528.   
  529.   // en cas de plantage, on aura au moins le cache!
  530.   fflush(cache_dat); fflush(cache_ndx);
  531. }
  532.  
  533. #endif
  534.  
  535.  
  536. htsblk cache_read(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location) {
  537.   return cache_readex(opt,cache,adr,fil,save,location,NULL,0);
  538. }
  539.  
  540. htsblk cache_read_ro(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location) {
  541.   return cache_readex(opt,cache,adr,fil,save,location,NULL,1);
  542. }
  543.  
  544. static htsblk cache_readex_old(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location,
  545.                                char* return_save, int readonly);
  546.  
  547. static htsblk cache_readex_new(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location,
  548.                                char* return_save, int readonly);
  549.  
  550. // lecture d'un fichier dans le cache
  551. // si save==null alors test unqiquement
  552. htsblk cache_readex(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location,
  553.                     char* return_save, int readonly) {
  554.   if (cache->zipInput != NULL) {
  555.     return cache_readex_new(opt, cache, adr, fil, save, location, return_save, readonly);
  556.   } else {
  557.     return cache_readex_old(opt, cache, adr, fil, save, location, return_save, readonly);
  558.   }
  559. }
  560.  
  561. // lecture d'un fichier dans le cache
  562. // si save==null alors test unqiquement
  563. static htsblk cache_readex_new(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location,
  564.                                char* return_save, int readonly) {
  565.   char BIGSTK location_default[HTS_URLMAXSIZE*2];
  566.   char BIGSTK buff[HTS_URLMAXSIZE*2];
  567.   char BIGSTK previous_save[HTS_URLMAXSIZE*2];
  568.   char BIGSTK previous_save_[HTS_URLMAXSIZE*2];
  569.     char catbuff[CATBUFF_SIZE];
  570.   intptr_t hash_pos;
  571.   int hash_pos_return;
  572.   htsblk r;
  573.   memset(&r, 0, sizeof(htsblk)); r.soc=INVALID_SOCKET;
  574.     location_default[0] = '\0';
  575.     previous_save[0] = previous_save_[0] = '\0';
  576.  
  577.   if (location) {
  578.     r.location = location;
  579.   } else {
  580.     r.location = location_default;
  581.   }
  582.   strcpybuff(r.location, ""); 
  583.   strcpybuff(buff, adr);
  584.   strcatbuff(buff,fil);
  585.   hash_pos_return = inthash_read(cache->hashtable, buff, &hash_pos);
  586.   /* avoid errors on data entries */
  587.   if (adr[0] == '/' && adr[1] == '/' && adr[2] == '[') {
  588. #if HTS_FAST_CACHE
  589.     hash_pos_return = 0;
  590. #else
  591.     a = NULL;
  592. #endif
  593.   }
  594.  
  595.   if (hash_pos_return) {
  596.     uLong posInZip;
  597.     if (hash_pos > 0) {
  598.       posInZip = (uLong) hash_pos;
  599.     } else {
  600.       posInZip = (uLong) -hash_pos;
  601.     }
  602.     if (unzSetOffset((unzFile) cache->zipInput, posInZip) == Z_OK) {
  603.       /* Read header (Max 8KiB) */
  604.       if (unzOpenCurrentFile((unzFile) cache->zipInput) == Z_OK) {
  605.         char BIGSTK headerBuff[8192 + 2];
  606.         int readSizeHeader;
  607.         int totalHeader = 0;
  608.         int dataincache = 0;
  609.         
  610.         /* For BIG comments */
  611.         headerBuff[0] 
  612.           = headerBuff[sizeof(headerBuff) - 1] 
  613.           = headerBuff[sizeof(headerBuff) - 2] 
  614.           = headerBuff[sizeof(headerBuff) - 3] = '\0';
  615.  
  616.         if ( (readSizeHeader = unzGetLocalExtrafield((unzFile) cache->zipInput, headerBuff, sizeof(headerBuff) - 2)) > 0) 
  617.         /*if (unzGetCurrentFileInfo((unzFile) cache->zipInput, NULL,
  618.           NULL, 0, NULL, 0, headerBuff, sizeof(headerBuff) - 2) == Z_OK ) */
  619.         {
  620.           int offset = 0;
  621.           char BIGSTK line[HTS_URLMAXSIZE + 2];
  622.           int lineEof = 0;
  623.           /*readSizeHeader = (int) strlen(headerBuff);*/
  624.           headerBuff[readSizeHeader] = '\0';
  625.           do {
  626.             char* value;
  627.             line[0] = '\0';
  628.             offset += binput(headerBuff + offset, line, sizeof(line) - 2);
  629.             if (line[0] == '\0') {
  630.               lineEof = 1;
  631.             }
  632.             value = strchr(line, ':');
  633.             if (value != NULL) {
  634.               *value++ = '\0';
  635.               if (*value == ' ' || *value == '\t') value++;
  636.               ZIP_READFIELD_INT(line, value, "X-In-Cache", dataincache);
  637.               ZIP_READFIELD_INT(line, value, "X-Statuscode", r.statuscode);
  638.               ZIP_READFIELD_STRING(line, value, "X-StatusMessage", r.msg);              // msg
  639.               ZIP_READFIELD_INT(line, value, "X-Size", r.size);           // size
  640.               ZIP_READFIELD_STRING(line, value, "Content-Type", r.contenttype);      // contenttype
  641.               ZIP_READFIELD_STRING(line, value, "X-Charset", r.charset);          // contenttype
  642.               ZIP_READFIELD_STRING(line, value, "Last-Modified", r.lastmodified);     // last-modified
  643.               ZIP_READFIELD_STRING(line, value, "Etag", r.etag);             // Etag
  644.               ZIP_READFIELD_STRING(line, value, "Location", r.location);         // 'location' pour moved
  645.               ZIP_READFIELD_STRING(line, value, "Content-Disposition", r.cdispo);           // Content-disposition
  646.               //ZIP_READFIELD_STRING(line, value, "X-Addr", ..);            // Original address
  647.               //ZIP_READFIELD_STRING(line, value, "X-Fil", ..);            // Original URI filename
  648.               ZIP_READFIELD_STRING(line, value, "X-Save", previous_save_);           // Original save filename
  649.             }
  650.           } while(offset < readSizeHeader && !lineEof);
  651.           totalHeader = offset;
  652.  
  653.                     /* Previous entry */
  654.                     if (previous_save_[0] != '\0') {
  655.                         int pathLen = (int) strlen(StringBuff(opt->path_html));
  656.                         if (pathLen != 0 && strncmp(previous_save_, StringBuff(opt->path_html), pathLen) != 0) {            // old (<3.40) buggy format
  657.                             sprintf(previous_save, "%s%s", StringBuff(opt->path_html), previous_save_);
  658.                         } else {
  659.                             strcpy(previous_save, previous_save_);
  660.                         }
  661.                     }
  662.           if (return_save != NULL) {
  663.             strcpybuff(return_save, previous_save);
  664.           }
  665.  
  666.           /* Complete fields */
  667.           r.totalsize=r.size;
  668.           r.adr=NULL;
  669.           r.out=NULL;
  670.           r.fp=NULL;
  671.           
  672.           if (save != NULL) {     /* ne pas lire uniquement header */
  673.             int ok = 0;
  674.                        
  675. #if HTS_DIRECTDISK
  676.             // Court-circuit:
  677.             // Peut-on stocker le fichier directement sur disque?
  678.             if (ok) {
  679.               if (r.msg[0] == '\0') {
  680.                 strcpybuff(r.msg,"Cache Read Error : Unexpected error");
  681.               }
  682.             }
  683.             else if (!readonly && r.statuscode==HTTP_OK && !is_hypertext_mime(opt,r.contenttype, fil) && strnotempty(save)) {    // pas HTML, Θcrire sur disk directement
  684.               
  685.               r.is_write=1;    // Θcrire
  686.                             if (!dataincache) {
  687.                                 if (fexist(fconv(catbuff, save))) {  // un fichier existe dΘja
  688.                                     //if (fsize(fconv(save))==r.size) {  // mΩme taille -- NON tant pis (taille mal declaree)
  689.                                     ok=1;    // plus rien α faire
  690.                                     filenote(&opt->state.strc,save,NULL);        // noter comme connu
  691.                                     file_notify(opt,adr, fil, save, 0, 0, 1);        // data in cache
  692.                                 }
  693.                             }
  694.               
  695.               if (!dataincache && !ok) { // Pas de donnΘe en cache et fichier introuvable : erreur!
  696.                 if (opt->norecatch) {
  697.                   file_notify(opt,adr, fil, save, 1, 0, 0);
  698.                   filecreateempty(&opt->state.strc, save);
  699.                   //
  700.                   r.statuscode=STATUSCODE_INVALID;
  701.                   strcpybuff(r.msg,"File deleted by user not recaught");
  702.                   ok=1;     // ne pas rΘcupΘrer (et pas d'erreur)
  703.                 } else {
  704.                   file_notify(opt,adr, fil, save, 1, 1, 0);
  705.                   r.statuscode=STATUSCODE_INVALID;
  706.                   strcpybuff(r.msg,"Previous cache file not found");
  707.                   ok=1;    // ne pas rΘcupΘrer
  708.                 }
  709.               }
  710.               
  711.               if (!ok) {        // load from cache
  712.                 file_notify(opt,adr, fil, save, 1, 1, 1);        // data in cache
  713.                 r.out=filecreate(&opt->state.strc, save);
  714. #if HDEBUG
  715.                 printf("direct-disk: %s\n",save);
  716. #endif
  717.                 if (r.out!=NULL) {
  718.                   char BIGSTK buff[32768+4];
  719.                   LLint size = r.size;
  720.                   if (size > 0) {
  721.                     size_t nl;
  722.                     do {
  723.                       nl = unzReadCurrentFile((unzFile) cache->zipInput, buff, (int)minimum(size, 32768));
  724.                       if (nl>0) {
  725.                         size-=nl; 
  726.                         if (fwrite(buff,1,nl,r.out)!=nl) {  // erreur
  727.                           int last_errno = errno;
  728.                           r.statuscode=STATUSCODE_INVALID;
  729.                           sprintf(r.msg,"Cache Read Error : Read To Disk: %s", strerror(last_errno));
  730.                         }
  731.                       }
  732.                     } while((nl>0) && (size>0) && (r.statuscode!=-1));
  733.                   }
  734.                   
  735.                   fclose(r.out);
  736.                   r.out=NULL;
  737. #ifndef _WIN32
  738.                   chmod(save,HTS_ACCESS_FILE);      
  739. #endif          
  740.                 } else {
  741.                   r.statuscode=STATUSCODE_INVALID;
  742.                   strcpybuff(r.msg,"Cache Write Error : Unable to Create File");
  743.                   //printf("%s\n",save);
  744.                 }
  745.               }
  746.               
  747.             } else
  748. #endif
  749.             { // lire en mΘmoire
  750.               
  751.               if (!dataincache) {
  752.                 if (strnotempty(save)) { // Pas de donnΘe en cache, bizarre car html!!!
  753.                   r.statuscode=STATUSCODE_INVALID;
  754.                   strcpybuff(r.msg,"Previous cache file not found (2)");
  755.                 } else {                 /* Read in memory from cache */
  756.                   if (strnotempty(previous_save) && fexist(previous_save)) {
  757.                     FILE* fp = fopen(fconv(catbuff, previous_save), "rb");
  758.                     if (fp != NULL) {
  759.                       r.adr = (char*) malloct((int) r.size + 4);
  760.                       if (r.adr != NULL) {
  761.                         if (r.size > 0 && fread(r.adr, 1, (int) r.size, fp) != r.size) {
  762.                           int last_errno = errno;
  763.                           r.statuscode=STATUSCODE_INVALID;
  764.                           sprintf(r.msg,"Read error in cache disk data: %s", strerror(last_errno));
  765.                         }
  766.                       } else {
  767.                         r.statuscode=STATUSCODE_INVALID;
  768.                         strcpybuff(r.msg,"Read error (memory exhausted) from cache");
  769.                       }
  770.                       fclose(fp);
  771.                     }
  772.                   } else {
  773.                     r.statuscode=STATUSCODE_INVALID;
  774.                     strcpybuff(r.msg,"Cache file not found on disk");
  775.                   }
  776.                 }
  777.               } else {
  778.                 // lire fichier (d'un coup)
  779.                 r.adr = (char*) malloct((int) r.size+4);
  780.                 if (r.adr!=NULL) {
  781.                   if (unzReadCurrentFile((unzFile) cache->zipInput, r.adr, (int) r.size) != r.size) {  // erreur
  782.                     freet(r.adr);
  783.                     r.adr=NULL;
  784.                     r.statuscode=STATUSCODE_INVALID;
  785.                     strcpybuff(r.msg,"Cache Read Error : Read Data");
  786.                   } else
  787.                     *(r.adr+r.size)='\0';
  788.                   //printf(">%s status %d\n",back[p].r.contenttype,back[p].r.statuscode);
  789.                 } else {  // erreur
  790.                   r.statuscode=STATUSCODE_INVALID;
  791.                   strcpybuff(r.msg,"Cache Memory Error");
  792.                 }
  793.               }
  794.             }
  795.           }    // si save==null, ne rien charger (juste en tΩte)
  796.  
  797.  
  798.         } else {
  799.           r.statuscode=STATUSCODE_INVALID;
  800.           strcpybuff(r.msg,"Cache Read Error : Read Header Data");
  801.         }
  802.         unzCloseCurrentFile((unzFile) cache->zipInput);
  803.       } else {
  804.         r.statuscode=STATUSCODE_INVALID;
  805.         strcpybuff(r.msg,"Cache Read Error : Open File");
  806.       }
  807.  
  808.     } else {
  809.       r.statuscode=STATUSCODE_INVALID;
  810.       strcpybuff(r.msg,"Cache Read Error : Bad Offset");
  811.     }
  812.   } else {
  813.     r.statuscode=STATUSCODE_INVALID;
  814.     strcpybuff(r.msg,"File Cache Entry Not Found");
  815.   }
  816.   if (!location) {   /* don't export internal buffer */
  817.     r.location = NULL;
  818.   }
  819.   return r;
  820. }
  821.  
  822.  
  823. // lecture d'un fichier dans le cache
  824. // si save==null alors test unqiquement
  825. static htsblk cache_readex_old(httrackp* opt,cache_back* cache,const char* adr,const char* fil,const char* save,char* location,
  826.                                char* return_save, int readonly) {
  827. #if HTS_FAST_CACHE
  828.   intptr_t hash_pos;
  829.   int hash_pos_return;
  830. #else
  831.   char* a;
  832. #endif
  833.   char BIGSTK buff[HTS_URLMAXSIZE*2];
  834.   char BIGSTK location_default[HTS_URLMAXSIZE*2];
  835.   char BIGSTK previous_save[HTS_URLMAXSIZE*2];
  836.     char catbuff[CATBUFF_SIZE];
  837.   htsblk r;
  838.   int ok=0;
  839.   int header_only=0;
  840.  
  841.   memset(&r, 0, sizeof(htsblk)); r.soc=INVALID_SOCKET;
  842.   if (location) {
  843.     r.location = location;
  844.   } else {
  845.     r.location = location_default;
  846.   }
  847.   strcpybuff(r.location, ""); 
  848. #if HTS_FAST_CACHE
  849.   strcpybuff(buff,adr); strcatbuff(buff,fil);
  850.   hash_pos_return=inthash_read(cache->hashtable,buff,&hash_pos);
  851. #else
  852.   buff[0]='\0'; strcatbuff(buff,"\n"); strcatbuff(buff,adr); strcatbuff(buff,"\n"); strcatbuff(buff,fil); strcatbuff(buff,"\n");
  853.   if (cache->use)
  854.     a=strstr(cache->use,buff);
  855.   else
  856.     a=NULL;       // forcer erreur
  857. #endif
  858.  
  859.   /* avoid errors on data entries */
  860.   if (adr[0] == '/' && adr[1] == '/' && adr[2] == '[') {
  861. #if HTS_FAST_CACHE
  862.     hash_pos_return = 0;
  863. #else
  864.     a = NULL;
  865. #endif
  866.   }
  867.  
  868.   // en cas de succΦs
  869. #if HTS_FAST_CACHE
  870.   if (hash_pos_return) {
  871. #else
  872.   if (a!=NULL) {  // OK existe en cache!
  873. #endif
  874.     intptr_t pos;
  875. #if DEBUGCA
  876.     fprintf(stdout,"..cache: %s%s at ",adr,fil);
  877. #endif
  878.     
  879. #if HTS_FAST_CACHE
  880.     pos = hash_pos;     /* simply */
  881. #else
  882.     a+=strlen(buff);
  883.     sscanf(a,"%d",&pos);    // lire position
  884. #endif
  885. #if DEBUGCA
  886.     printf("%d\n",pos);
  887. #endif
  888.  
  889.     fflush(cache->olddat); 
  890.     if (fseek(cache->olddat,(long)((pos>0)?pos:(-pos)),SEEK_SET) == 0) {
  891.       /* Importer cache1.0 */
  892.       if (cache->version==0) {
  893.         OLD_htsblk old_r;
  894.         if (fread((char*) &old_r,1,sizeof(old_r),cache->olddat)==sizeof(old_r)) { // lire tout (y compris statuscode etc)
  895.           r.statuscode=old_r.statuscode;
  896.           r.size=old_r.size;        // taille fichier
  897.           strcpybuff(r.msg,old_r.msg);
  898.           strcpybuff(r.contenttype,old_r.contenttype);
  899.           ok=1;     /* import  ok */
  900.         }
  901.       /* */
  902.       /* Cache 1.1 */
  903.       } else {
  904.         char check[256];
  905.         LLint size_read;
  906.         check[0]='\0';
  907.         //
  908.         cache_rint(cache->olddat,&r.statuscode);
  909.         cache_rLLint(cache->olddat,&r.size);
  910.         cache_rstr(cache->olddat,r.msg);
  911.         cache_rstr(cache->olddat,r.contenttype);
  912.         if (cache->version >= 3)
  913.           cache_rstr(cache->olddat,r.charset);
  914.         cache_rstr(cache->olddat,r.lastmodified);
  915.         cache_rstr(cache->olddat,r.etag);
  916.         cache_rstr(cache->olddat,r.location);
  917.         if (cache->version >= 2)
  918.           cache_rstr(cache->olddat,r.cdispo);
  919.         if (cache->version >= 4) {
  920.           cache_rstr(cache->olddat, previous_save);  // adr
  921.           cache_rstr(cache->olddat, previous_save);  // fil
  922.           previous_save[0] = '\0';
  923.           cache_rstr(cache->olddat, previous_save);  // save
  924.           if (return_save != NULL) {
  925.             strcpybuff(return_save, previous_save);
  926.           }
  927.         }
  928.         if (cache->version >= 5) {
  929.           r.headers = cache_rstr_addr(cache->olddat);
  930.         }
  931.         //
  932.         cache_rstr(cache->olddat,check);
  933.         if (strcmp(check,"HTS")==0) {           /* intΘgritΘ OK */
  934.           ok=1;
  935.         }
  936.         cache_rLLint(cache->olddat,&size_read);       /* lire size pour Ωtre s√r de la taille dΘclarΘe (rΘΘcrire) */
  937.         if (size_read>0) {                         /* si inscrite ici */
  938.           r.size=size_read;
  939.         } else {                              /* pas de donnΘes directement dans le cache, fichier prΘsent? */
  940.           if (r.statuscode!=HTTP_OK)
  941.             header_only=1;          /* que l'en tΩte ici! */
  942.         }
  943.       }
  944.  
  945.       /* Remplir certains champs */
  946.       r.totalsize=r.size;
  947.  
  948.       // lecture du header (y compris le statuscode)
  949.       /*if (fread((char*) &r,1,sizeof(htsblk),cache->olddat)==sizeof(htsblk)) { // lire tout (y compris statuscode etc)*/
  950.       if (ok) {
  951.         // sΘcuritΘ
  952.         r.adr=NULL;
  953.         r.out=NULL;
  954.         ////r.location=NULL;  non, fixΘe lors des 301 ou 302
  955.         r.fp=NULL;
  956.         
  957.         if ( (r.statuscode>=0) && (r.statuscode<=999)
  958.           && (r.notmodified>=0)  && (r.notmodified<=9) ) {   // petite vΘrif intΘgritΘ
  959.           if ((save) && (!header_only) ) {     /* ne pas lire uniquement header */
  960.             //int to_file=0;
  961.             
  962.             r.adr=NULL; r.soc=INVALID_SOCKET; 
  963.             // // r.location=NULL;
  964.             
  965. #if HTS_DIRECTDISK
  966.             // Court-circuit:
  967.             // Peut-on stocker le fichier directement sur disque?
  968.             if (!readonly && r.statuscode==HTTP_OK && !is_hypertext_mime(opt,r.contenttype, fil) && strnotempty(save)) {    // pas HTML, Θcrire sur disk directement
  969.               int ok=0;
  970.               
  971.               r.is_write=1;    // Θcrire
  972.               if (fexist(fconv(catbuff, save))) {  // un fichier existe dΘja
  973.                 //if (fsize(fconv(save))==r.size) {  // mΩme taille -- NON tant pis (taille mal declaree)
  974.                 ok=1;    // plus rien α faire
  975.                 filenote(&opt->state.strc,save,NULL);        // noter comme connu
  976.                 file_notify(opt,adr, fil, save, 0, 0, 0);
  977.                 //}
  978.               }
  979.               
  980.               if ((pos<0) && (!ok)) { // Pas de donnΘe en cache et fichier introuvable : erreur!
  981.                 if (opt->norecatch) {
  982.                   file_notify(opt,adr, fil, save, 1, 0, 0);
  983.                   filecreateempty(&opt->state.strc, save);
  984.                   //
  985.                   r.statuscode=STATUSCODE_INVALID;
  986.                   strcpybuff(r.msg,"File deleted by user not recaught");
  987.                   ok=1;     // ne pas rΘcupΘrer (et pas d'erreur)
  988.                 } else {
  989.                   r.statuscode=STATUSCODE_INVALID;
  990.                   strcpybuff(r.msg,"Previous cache file not found");
  991.                   ok=1;    // ne pas rΘcupΘrer
  992.                 }
  993.               }
  994.               
  995.               if (!ok) {  
  996.                 r.out=filecreate(&opt->state.strc, save);
  997. #if HDEBUG
  998.                 printf("direct-disk: %s\n",save);
  999. #endif
  1000.                 if (r.out!=NULL) {
  1001.                   char BIGSTK buff[32768+4];
  1002.                   size_t size = (size_t) r.size;
  1003.                   if (size > 0) {
  1004.                     size_t nl;
  1005.                     do {
  1006.                       nl=fread(buff,1,minimum(size,32768),cache->olddat);
  1007.                       if (nl>0) {
  1008.                         size-=nl; 
  1009.                         if (fwrite(buff,1,nl,r.out)!=nl) {  // erreur
  1010.                           r.statuscode=STATUSCODE_INVALID;
  1011.                           strcpybuff(r.msg,"Cache Read Error : Read To Disk");
  1012.                         }
  1013.                       }
  1014.                     } while((nl>0) && (size>0) && (r.statuscode!=-1));
  1015.                   }
  1016.                   
  1017.                   fclose(r.out);
  1018.                   r.out=NULL;
  1019. #ifndef _WIN32
  1020.                   chmod(save,HTS_ACCESS_FILE);      
  1021. #endif          
  1022.                 } else {
  1023.                   r.statuscode=STATUSCODE_INVALID;
  1024.                   strcpybuff(r.msg,"Cache Write Error : Unable to Create File");
  1025.                   //printf("%s\n",save);
  1026.                 }
  1027.               }
  1028.               
  1029.             } else
  1030. #endif
  1031.             { // lire en mΘmoire
  1032.               
  1033.               if (pos<0) {
  1034.                 if (strnotempty(save)) { // Pas de donnΘe en cache, bizarre car html!!!
  1035.                   r.statuscode=STATUSCODE_INVALID;
  1036.                   strcpybuff(r.msg,"Previous cache file not found (2)");
  1037.                 } else {                 /* Read in memory from cache */
  1038.                   if (strnotempty(return_save) && fexist(return_save)) {
  1039.                     FILE* fp = fopen(fconv(catbuff, return_save), "rb");
  1040.                     if (fp != NULL) {
  1041.                       r.adr = (char*) malloct((size_t)r.size + 4);
  1042.                       if (r.adr != NULL) {
  1043.                         if (r.size > 0 && fread(r.adr, 1, (size_t)r.size, fp) != r.size) {
  1044.                           r.statuscode=STATUSCODE_INVALID;
  1045.                           strcpybuff(r.msg,"Read error in cache disk data");
  1046.                         }
  1047.                       } else {
  1048.                         r.statuscode=STATUSCODE_INVALID;
  1049.                         strcpybuff(r.msg,"Read error (memory exhausted) from cache");
  1050.                       }
  1051.                       fclose(fp);
  1052.                     }
  1053.                   } else {
  1054.                     r.statuscode=STATUSCODE_INVALID;
  1055.                     strcpybuff(r.msg,"Cache file not found on disk");
  1056.                   }
  1057.                 }
  1058.               } else {
  1059.                 // lire fichier (d'un coup)
  1060.                 r.adr=(char*) malloct((size_t)r.size+4);
  1061.                 if (r.adr!=NULL) {
  1062.                   if (fread(r.adr,1,(size_t)r.size,cache->olddat)!=r.size) {  // erreur
  1063.                     freet(r.adr);
  1064.                     r.adr=NULL;
  1065.                     r.statuscode=STATUSCODE_INVALID;
  1066.                     strcpybuff(r.msg,"Cache Read Error : Read Data");
  1067.                   } else
  1068.                     *(r.adr+r.size)='\0';
  1069.                   //printf(">%s status %d\n",back[p].r.contenttype,back[p].r.statuscode);
  1070.                 } else {  // erreur
  1071.                   r.statuscode=STATUSCODE_INVALID;
  1072.                   strcpybuff(r.msg,"Cache Memory Error");
  1073.                 }
  1074.               }
  1075.             }
  1076.           }    // si save==null, ne rien charger (juste en tΩte)
  1077.         } else {
  1078. #if DEBUGCA
  1079.           printf("Cache Read Error : Bad Data");
  1080. #endif
  1081.           r.statuscode=STATUSCODE_INVALID;
  1082.           strcpybuff(r.msg,"Cache Read Error : Bad Data");
  1083.         }
  1084.       } else {  // erreur
  1085. #if DEBUGCA
  1086.         printf("Cache Read Error : Read Header");
  1087. #endif
  1088.         r.statuscode=STATUSCODE_INVALID;
  1089.         strcpybuff(r.msg,"Cache Read Error : Read Header");
  1090.       }
  1091.     } else {
  1092. #if DEBUGCA
  1093.       printf("Cache Read Error : Seek Failed");
  1094. #endif
  1095.       r.statuscode=STATUSCODE_INVALID;
  1096.       strcpybuff(r.msg,"Cache Read Error : Seek Failed");
  1097.     }
  1098.   } else {
  1099. #if DEBUGCA
  1100.     printf("File Cache Not Found");
  1101. #endif
  1102.     r.statuscode=STATUSCODE_INVALID;
  1103.     strcpybuff(r.msg,"File Cache Entry Not Found");
  1104.   }
  1105.   if (!location) {   /* don't export internal buffer */
  1106.     r.location = NULL;
  1107.   }
  1108.   return r;
  1109. }
  1110.  
  1111. /* write (string1-string2)-data in cache */
  1112. /* 0 if failed */
  1113. int cache_writedata(FILE* cache_ndx,FILE* cache_dat,const char* str1,const char* str2,char* outbuff,int len) {
  1114.   if (cache_dat) {
  1115.     char BIGSTK buff[HTS_URLMAXSIZE*4];
  1116.     char s[256];
  1117.     int pos;
  1118.     fflush(cache_dat); fflush(cache_ndx);
  1119.     pos=ftell(cache_dat);
  1120.     /* first write data */
  1121.     if (cache_wint(cache_dat,len)!=-1) {       // length
  1122.       if (fwrite(outbuff,1,len,cache_dat) == len) {   // data
  1123.         /* then write index */
  1124.         sprintf(s,"%d\n",pos);
  1125.         buff[0]='\0'; strcatbuff(buff,str1); strcatbuff(buff,"\n"); strcatbuff(buff,str2); strcatbuff(buff,"\n");
  1126.         cache_wstr(cache_ndx,buff);
  1127.         if (fwrite(s,1,strlen(s),cache_ndx) == strlen(s)) {
  1128.           fflush(cache_dat); fflush(cache_ndx);
  1129.           return 1;
  1130.         }
  1131.       }
  1132.     }
  1133.   }
  1134.   return 0;
  1135. }
  1136.  
  1137. /* read the data corresponding to (string1-string2) in cache */
  1138. /* 0 if failed */
  1139. int cache_readdata(cache_back* cache,const char* str1,const char* str2,char** inbuff,int* inlen) {
  1140. #if HTS_FAST_CACHE
  1141.   if (cache->hashtable) {
  1142.     char BIGSTK buff[HTS_URLMAXSIZE*4];
  1143.     intptr_t pos;
  1144.     strcpybuff(buff,str1); strcatbuff(buff,str2);
  1145.     if (inthash_read(cache->hashtable,buff,&pos)) {
  1146.       if (fseek(cache->olddat,(long)((pos>0)?pos:(-pos)),SEEK_SET) == 0) {
  1147.         INTsys len;
  1148.         cache_rint(cache->olddat,&len);
  1149.         if (len>0) {
  1150.           char* mem_buff=(char*)malloct(len+4);    /* Plus byte 0 */
  1151.           if (mem_buff) {
  1152.             if (fread(mem_buff,1,len,cache->olddat)==len) { // lire tout (y compris statuscode etc)*/
  1153.               *inbuff=mem_buff;
  1154.               *inlen=len;
  1155.               return 1;
  1156.             } else
  1157.               freet(mem_buff);
  1158.           }
  1159.         }
  1160.       }
  1161.     }
  1162.   }
  1163. #endif
  1164.   *inbuff=NULL;
  1165.   *inlen=0;
  1166.   return 0;
  1167. }
  1168.  
  1169. static int hts_rename(httrackp* opt, const char *a, const char *b) {
  1170.   if ((opt->debug>0) && (opt->log!=NULL)) {
  1171.     HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: rename %s -> %s (%p %p)"LF, a, b, a, b);
  1172.   }
  1173.   return rename(a, b);
  1174. }
  1175.  
  1176. // renvoyer uniquement en tΩte, ou NULL si erreur
  1177. // return NULL upon error, and set -1 to r.statuscode
  1178. htsblk* cache_header(httrackp* opt,cache_back* cache,const char* adr,const char* fil,htsblk* r) {
  1179.   *r=cache_read(opt,cache,adr,fil,NULL,NULL);              // test uniquement
  1180.   if (r->statuscode != -1)
  1181.     return r;
  1182.   else
  1183.     return NULL;
  1184. }
  1185.  
  1186.  
  1187. // Initialisation du cache: crΘer nouveau, renomer ancien, charger..
  1188. void cache_init(cache_back* cache,httrackp* opt) {
  1189.   // ---
  1190.   // utilisation du cache: renommer ancien Θventuel et charger index
  1191.   if ((opt->debug>0) && (opt->log!=NULL)) {
  1192.     HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: enabled=%d, base=%s, ro=%d"LF, (int) opt->cache, fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/"), (int) cache->ro);
  1193.   }
  1194.   if (opt->cache) {
  1195. #if DEBUGCA
  1196.     printf("cache init: ");
  1197. #endif
  1198.     if (!cache->ro) {
  1199. #ifdef _WIN32
  1200.       mkdir(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache"));
  1201. #else
  1202.       mkdir(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache"),HTS_PROTECT_FOLDER);
  1203. #endif
  1204.       if ((fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip")))) {  // il existe dΘja un cache prΘcΘdent.. renommer
  1205.         /* Previous cache from the previous cache version */
  1206. #if 0
  1207.         /* No.. reuse with old httrack releases! */
  1208.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat")))
  1209.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat"));
  1210.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx")))
  1211.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1212. #endif
  1213.         /* Previous cache version */
  1214.         if ((fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"))) && (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx")))) {  // il existe dΘja un cache prΘcΘdent.. renommer
  1215.           rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat"));
  1216.           rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1217.         }
  1218.  
  1219.         /* Remove OLD cache */
  1220.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip"))) {
  1221.           if (remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip")) != 0) {
  1222.             int last_errno = errno;
  1223.             if (opt->log!=NULL) {
  1224.               HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: error while moving previous cache: %s"LF, strerror(last_errno));
  1225.             }
  1226.           }
  1227.         }
  1228.         
  1229.         /* Rename */
  1230.         if (hts_rename(opt, fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip"), fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip")) != 0) {
  1231.           int last_errno = errno;
  1232.           if (opt->log!=NULL) {
  1233.             HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: error while moving previous cache: %s"LF, strerror(last_errno));
  1234.           }
  1235.         } else {
  1236.           if ((opt->debug>0) && (opt->log!=NULL)) {
  1237.             HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: successfully renamed"LF);
  1238.           }
  1239.         }
  1240.       }
  1241.       else if ((fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"))) && (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx")))) {  // il existe dΘja un cache prΘcΘdent.. renommer
  1242. #if DEBUGCA
  1243.         printf("work with former cache\n");
  1244. #endif
  1245.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat")))
  1246.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat"));
  1247.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx")))
  1248.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1249.         
  1250.         rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat"));
  1251.         rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1252.       } else {  // un des deux (ou les deux) fichiers cache absents: effacer l'autre Θventuel
  1253. #if DEBUGCA
  1254.         printf("new cache\n");
  1255. #endif
  1256.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat")))
  1257.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"));
  1258.         if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx")))
  1259.           remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"));
  1260.       }
  1261.     } else {
  1262.       if ((opt->debug>0) && (opt->log!=NULL)) {
  1263.         HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: no cache found"LF);
  1264.       }
  1265.     }
  1266.     if ((opt->debug>0) && (opt->log!=NULL)) {
  1267.       HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: size %d"LF, fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip")));
  1268.     }
  1269.  
  1270.     // charger index cache prΘcΘdent
  1271.     if (
  1272.       (
  1273.       !cache->ro &&
  1274.       fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip")) > 0 
  1275.       )
  1276.       ||
  1277.       (
  1278.       cache->ro &&
  1279.       fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip")) > 0
  1280.       )
  1281.       ) 
  1282.     {
  1283.       if (!cache->ro) {
  1284.         cache->zipInput = unzOpen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip"));
  1285.       } else {
  1286.         cache->zipInput = unzOpen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip"));
  1287.       }
  1288.       
  1289.       // Corrupted ZIP file ? Try to repair!
  1290.       if (cache->zipInput == NULL && !cache->ro) {
  1291.         char* name;
  1292.         uLong repaired = 0;
  1293.         uLong repairedBytes = 0;
  1294.         if (!cache->ro) {
  1295.           name = fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.zip");
  1296.         } else {
  1297.           name = fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip");
  1298.         }
  1299.         if (opt->log) {
  1300.           HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: damaged cache, trying to repair"LF);
  1301.           fflush(opt->log);
  1302.         }
  1303.         if (unzRepair(name, 
  1304.           fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/repair.zip"),
  1305.           fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/repair.tmp"),
  1306.           &repaired, &repairedBytes
  1307.           ) == Z_OK) {
  1308.             unlink(name);
  1309.             rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/repair.zip"), name);
  1310.             cache->zipInput = unzOpen(name);
  1311.             if (opt->log) {
  1312.               HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: %d bytes successfully recovered in %d entries"LF, 
  1313.                 (int) repairedBytes, (int) repaired);
  1314.               fflush(opt->log);
  1315.             }
  1316.           } else {
  1317.             if (opt->log) {
  1318.               HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: could not repair the cache"LF);
  1319.               fflush(opt->log);
  1320.             }
  1321.           }
  1322.       }
  1323.       
  1324.       // Opened ?
  1325.       if (cache->zipInput!=NULL) {
  1326.         int zErr;
  1327.  
  1328.         /* Ready directory entries */
  1329.         if ( ( zErr = unzGoToFirstFile((unzFile) cache->zipInput) ) == Z_OK) {
  1330.           char comment[128];
  1331.           char BIGSTK filename[HTS_URLMAXSIZE * 4];
  1332.           int entries = 0;
  1333.           memset(comment, 0, sizeof(comment));       // for truncated reads
  1334.           do  {
  1335.             int readSizeHeader = 0;
  1336.             filename[0] = '\0';
  1337.             comment[0] = '\0';
  1338.             if (unzOpenCurrentFile((unzFile) cache->zipInput) == Z_OK) {
  1339.               if (
  1340.                 (readSizeHeader = unzGetLocalExtrafield((unzFile) cache->zipInput, comment, sizeof(comment) - 2)) > 0
  1341.                 &&
  1342.                 unzGetCurrentFileInfo((unzFile) cache->zipInput, NULL, filename, sizeof(filename) - 2, NULL, 0, NULL, 0) == Z_OK
  1343.                 ) 
  1344.               {
  1345.                 long int pos = (long int) unzGetOffset((unzFile) cache->zipInput);
  1346.                 assertf(readSizeHeader < sizeof(comment));
  1347.                 comment[readSizeHeader] = '\0';
  1348.                 entries++;
  1349.                 if (pos > 0) {
  1350.                   int dataincache = 0;    // data in cache ?
  1351.                   char* filenameIndex = filename;
  1352.                   if (strfield(filenameIndex, "http://")) {
  1353.                     filenameIndex += 7;
  1354.                   }
  1355.                   if (comment[0] != '\0') {
  1356.                     int maxLine = 2;
  1357.                     char* a = comment;
  1358.                     while(*a && maxLine-- > 0) {      // parse only few first lines
  1359.                       char BIGSTK line[1024];
  1360.                       line[0] = '\0';
  1361.                       a+=binput(a, line, sizeof(line) - 2);
  1362.                       if (strfield(line, "X-In-Cache:")) {
  1363.                         if (strfield2(line, "X-In-Cache: 1")) {
  1364.                           dataincache = 1;
  1365.                         } else {
  1366.                           dataincache = 0;
  1367.                         }
  1368.                         break;
  1369.                       }
  1370.                     }
  1371.                   }
  1372.                   if (dataincache)
  1373.                     inthash_add(cache->hashtable, filenameIndex, pos);
  1374.                   else
  1375.                     inthash_add(cache->hashtable, filenameIndex, -pos);
  1376.                 } else {
  1377.                   if (opt->log!=NULL) {
  1378.                     HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Corrupted cache meta entry #%d"LF, (int)entries);
  1379.                   }
  1380.                 }
  1381.               } else {
  1382.                 if (opt->log!=NULL) {
  1383.                   HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Corrupted cache entry #%d"LF, (int)entries);
  1384.                 }
  1385.               }
  1386.               unzCloseCurrentFile((unzFile) cache->zipInput);
  1387.             } else {
  1388.               if (opt->log!=NULL) {
  1389.                 HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Corrupted cache entry #%d"LF, (int)entries);
  1390.               }
  1391.             }
  1392.           } while( unzGoToNextFile((unzFile) cache->zipInput) == Z_OK );
  1393.           if ((opt->debug>0) && (opt->log!=NULL)) {
  1394.             HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache index loaded: %d entries loaded"LF, (int)entries);
  1395.           }
  1396.           opt->is_update=1;        // signaler comme update
  1397.           
  1398.         } else {
  1399.           HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: error trying to read the cache: %s"LF, hts_get_zerror(zErr));
  1400.         }    
  1401.         
  1402.       } else {
  1403.         HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: error trying to open the cache"LF);
  1404.       }
  1405.       
  1406.     } else if (
  1407.       (
  1408.       !cache->ro &&
  1409.       fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat")) >=0 && fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx")) >0
  1410.       )
  1411.       ||
  1412.       (
  1413.       cache->ro &&
  1414.       fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat")) >=0 && fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx")) > 0
  1415.       )
  1416.       ) {
  1417.       FILE* oldndx=NULL;
  1418. #if DEBUGCA
  1419.       printf("..load cache\n");
  1420. #endif
  1421.       if (!cache->ro) {
  1422.         cache->olddat=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.dat"),"rb");        
  1423.         oldndx=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"),"rb");        
  1424.       } else {
  1425.         cache->olddat=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"),"rb");        
  1426.         oldndx=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"),"rb");        
  1427.       }
  1428.       // les deux doivent Ωtre ouvrables
  1429.       if ((cache->olddat==NULL) && (oldndx!=NULL)) {
  1430.         fclose(oldndx);
  1431.         oldndx=NULL;
  1432.       }
  1433.       if ((cache->olddat!=NULL) && (oldndx==NULL)) {
  1434.         fclose(cache->olddat);
  1435.         cache->olddat=NULL;
  1436.       }
  1437.       // lire index
  1438.       if (oldndx!=NULL) {
  1439.         int buffl;
  1440.         fclose(oldndx); oldndx=NULL;
  1441.         // lire ndx, et lastmodified
  1442.         if (!cache->ro) {
  1443.           buffl=fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1444.           cache->use=readfile(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.ndx"));
  1445.         } else {
  1446.           buffl=fsize(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"));
  1447.           cache->use=readfile(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"));
  1448.         }
  1449.         if (cache->use!=NULL) {
  1450.           char firstline[256];
  1451.           char* a=cache->use;
  1452.           a+=cache_brstr(a,firstline);
  1453.           if (strncmp(firstline,"CACHE-",6)==0) {       // Nouvelle version du cache
  1454.             if (strncmp(firstline,"CACHE-1.",8)==0) {      // Version 1.1x
  1455.               cache->version=(int)(firstline[8]-'0');           // cache 1.x
  1456.               if (cache->version <= 5) {
  1457.                 a+=cache_brstr(a,firstline);
  1458.                 strcpybuff(cache->lastmodified,firstline);
  1459.               } else {
  1460.                 if (opt->log) {
  1461.                   HTS_LOG(opt,LOG_ERROR); fprintf(opt->log,"Cache: version 1.%d not supported, ignoring current cache"LF,cache->version);
  1462.                   fflush(opt->log);
  1463.                 }
  1464.                 fclose(cache->olddat);
  1465.                 cache->olddat=NULL;
  1466.                 freet(cache->use);
  1467.                 cache->use=NULL;
  1468.               }
  1469.             } else {        // non supportΘ
  1470.               if (opt->log) {
  1471.                 HTS_LOG(opt,LOG_ERROR); fprintf(opt->log,"Cache: %s not supported, ignoring current cache"LF,firstline);
  1472.                 fflush(opt->log);
  1473.               }
  1474.               fclose(cache->olddat);
  1475.               cache->olddat=NULL;
  1476.               freet(cache->use);
  1477.               cache->use=NULL;
  1478.             }
  1479.             /* */
  1480.           } else {              // Vieille version du cache
  1481.             /* */
  1482.             if (opt->log) {
  1483.               HTS_LOG(opt,LOG_WARNING); fprintf(opt->log,"Cache: importing old cache format"LF);
  1484.               fflush(opt->log);
  1485.             }
  1486.             cache->version=0;        // cache 1.0
  1487.             strcpybuff(cache->lastmodified,firstline); 
  1488.           }
  1489.           opt->is_update=1;        // signaler comme update
  1490.           
  1491.           /* Create hash table for the cache (MUCH FASTER!) */
  1492. #if HTS_FAST_CACHE
  1493.           if (cache->use) {
  1494.             char BIGSTK line[HTS_URLMAXSIZE*2];
  1495.             char linepos[256];
  1496.             int  pos;
  1497.             while ( (a!=NULL) && (a < (cache->use+buffl) ) ) {
  1498.               a=strchr(a+1,'\n');     /* start of line */
  1499.               if (a) {
  1500.                 a++;
  1501.                 /* read "host/file" */
  1502.                 a+=binput(a,line,HTS_URLMAXSIZE);
  1503.                 a+=binput(a,line+strlen(line),HTS_URLMAXSIZE);
  1504.                 /* read position */
  1505.                 a+=binput(a,linepos,200);
  1506.                 sscanf(linepos,"%d",&pos);
  1507.                 inthash_add(cache->hashtable,line,pos);
  1508.               }
  1509.             }
  1510.             /* Not needed anymore! */
  1511.             freet(cache->use);
  1512.             cache->use=NULL;
  1513.           }
  1514. #endif
  1515.         }
  1516.       }
  1517.       } else {
  1518.         if ((opt->debug>0) && (opt->log!=NULL)) {
  1519.           HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: no cache found in %s"LF, fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/"));
  1520.         }
  1521.       }
  1522.  
  1523. #if DEBUGCA
  1524.       printf("..create cache\n");
  1525. #endif
  1526.       if (!cache->ro) {
  1527.         // ouvrir caches actuels
  1528.         structcheck(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log), "hts-cache/"));
  1529.  
  1530.         if (1) {
  1531.           /* Create ZIP file cache */
  1532.           cache->zipOutput = (void*) zipOpen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.zip"), 0);
  1533.  
  1534.           if (cache->zipOutput != NULL) {
  1535.             // supprimer old.lst
  1536.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst")))
  1537.               remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst"));
  1538.             // renommer
  1539.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst")))
  1540.               rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst"));
  1541.             // ouvrir
  1542.             cache->lst=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst"),"wb");
  1543.             strcpybuff(opt->state.strc.path, StringBuff(opt->path_html));
  1544.             opt->state.strc.lst = cache->lst;
  1545.             //{
  1546.             //filecreate_params tmp;
  1547.             //strcpybuff(tmp.path,StringBuff(opt->path_html));    // chemin
  1548.             //tmp.lst=cache->lst;                 // fichier lst
  1549.             //filenote("",&tmp);        // initialiser filecreate
  1550.             //}
  1551.  
  1552.             // supprimer old.txt
  1553.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.txt")))
  1554.               remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.txt"));
  1555.             // renommer
  1556.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt")))
  1557.               rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.txt"));
  1558.             // ouvrir
  1559.             cache->txt=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt"),"wb");
  1560.             if (cache->txt) {
  1561.               fprintf(cache->txt,"date\tsize'/'remotesize\tflags(request:Update,Range state:File response:Modified,Chunked,gZipped)\t");
  1562.               fprintf(cache->txt,"statuscode\tstatus ('servermsg')\tMIME\tEtag|Date\tURL\tlocalfile\t(from URL)"LF);
  1563.             }
  1564.           }
  1565.         } else {
  1566.           cache->dat=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.dat"),"wb");        
  1567.           cache->ndx=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.ndx"),"wb");        
  1568.           // les deux doivent Ωtre ouvrables
  1569.           if ((cache->dat==NULL) && (cache->ndx!=NULL)) {
  1570.             fclose(cache->ndx);
  1571.             cache->ndx=NULL;
  1572.           }
  1573.           if ((cache->dat!=NULL) && (cache->ndx==NULL)) {
  1574.             fclose(cache->dat);
  1575.             cache->dat=NULL;
  1576.           }
  1577.  
  1578.           if (cache->ndx!=NULL) {
  1579.             char s[256];
  1580.  
  1581.             cache_wstr(cache->dat,"CACHE-1.5");
  1582.             fflush(cache->dat);
  1583.             cache_wstr(cache->ndx,"CACHE-1.5");
  1584.             fflush(cache->ndx);
  1585.             //
  1586.             time_gmt_rfc822(s);   // date et heure actuelle GMT pour If-Modified-Since..
  1587.             cache_wstr(cache->ndx,s);        
  1588.             fflush(cache->ndx);    // un petit fflush au cas o∙
  1589.  
  1590.             // supprimer old.lst
  1591.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst")))
  1592.               remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst"));
  1593.             // renommer
  1594.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst")))
  1595.               rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst"),fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.lst"));
  1596.             // ouvrir
  1597.             cache->lst=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.lst"),"wb");
  1598.             strcpybuff(opt->state.strc.path, StringBuff(opt->path_html));
  1599.             opt->state.strc.lst = cache->lst;
  1600.             //{
  1601.             //  filecreate_params tmp;
  1602.             //  strcpybuff(tmp.path,StringBuff(opt->path_html));    // chemin
  1603.             //  tmp.lst=cache->lst;                 // fichier lst
  1604.             //  filenote("",&tmp);        // initialiser filecreate
  1605.             //}
  1606.  
  1607.             // supprimer old.txt
  1608.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.txt")))
  1609.               remove(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/old.txt"));
  1610.             // renommer
  1611.             if (fexist(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt")))
  1612.               rename(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt"),fconcat(OPT_GET_BUFF(opt),StringBuff(opt->path_log),"hts-cache/old.txt"));
  1613.             // ouvrir
  1614.             cache->txt=fopen(fconcat(OPT_GET_BUFF(opt), StringBuff(opt->path_log),"hts-cache/new.txt"),"wb");
  1615.             if (cache->txt) {
  1616.               fprintf(cache->txt,"date\tsize'/'remotesize\tflags(request:Update,Range state:File response:Modified,Chunked,gZipped)\t");
  1617.               fprintf(cache->txt,"statuscode\tstatus ('servermsg')\tMIME\tEtag|Date\tURL\tlocalfile\t(from URL)"LF);
  1618.             }
  1619.  
  1620.             // test
  1621.             // cache_writedata(cache->ndx,cache->dat,"//[TEST]//","test1","TEST PIPO",9);
  1622.           } // cache->ndx!=NULL
  1623.         } //cache->zipOutput != NULL
  1624.  
  1625.       } else {
  1626.         cache->lst = cache->dat = cache->ndx = NULL;
  1627.       }
  1628.       
  1629.   } else {
  1630.     if ((opt->debug>0) && (opt->log!=NULL)) {
  1631.       HTS_LOG(opt,LOG_DEBUG); fprintf(opt->log,"Cache: no cache enabled"LF);
  1632.     }
  1633.   }
  1634.   
  1635. }
  1636.  
  1637.  
  1638.  
  1639.  
  1640. // lire un fichier.. (compatible \0)
  1641. char* readfile(char* fil) {
  1642.   return readfile2(fil, NULL);
  1643. }
  1644.  
  1645. char* readfile2(char* fil, LLint* size) {
  1646.   char* adr=NULL;
  1647.     char catbuff[CATBUFF_SIZE];
  1648.   INTsys len=0;
  1649.   len=fsize(fil);
  1650.   if (len >= 0) {  // exists
  1651.     FILE* fp;
  1652.     fp=fopen(fconv(catbuff, fil),"rb");
  1653.     if (fp!=NULL) {  // n'existe pas (!)
  1654.       adr=(char*) malloct(len+1);
  1655.       if (size != NULL)
  1656.         *size = len;
  1657.       if (adr!=NULL) {
  1658.         if (len > 0 && fread(adr,1,len,fp) != len) {    // fichier endommagΘ ?
  1659.           freet(adr);
  1660.           adr=NULL;
  1661.         } else
  1662.           *(adr+len)='\0';
  1663.       }
  1664.       fclose(fp);
  1665.     }
  1666.   }
  1667.   return adr;
  1668. }
  1669.  
  1670. char* readfile_or(char* fil,char* defaultdata) {
  1671.   char* realfile=fil;
  1672.   char* ret;
  1673.     char catbuff[CATBUFF_SIZE];
  1674.   if (!fexist(fil))
  1675.     realfile=fconcat(catbuff,hts_rootdir(NULL),fil);
  1676.   ret=readfile(realfile);
  1677.   if (ret)
  1678.     return ret;
  1679.   else {
  1680.     char *adr=malloct(strlen(defaultdata)+2);
  1681.     if (adr) {
  1682.       strcpybuff(adr,defaultdata);
  1683.       return adr;
  1684.     }
  1685.   }
  1686.   return NULL;
  1687. }
  1688.  
  1689. // Θcriture/lecture d'une chaεne sur un fichier
  1690. // -1 : erreur, sinon 0
  1691. int cache_wstr(FILE* fp,const char* s) {
  1692.   INTsys i;
  1693.   char buff[256+4];
  1694.   i = (s != NULL) ? ((INTsys)strlen(s)) : 0;
  1695.   sprintf(buff,INTsysP "\n",i);
  1696.   if (fwrite(buff,1,strlen(buff),fp) != strlen(buff))
  1697.     return -1;
  1698.   if (i > 0 && fwrite(s,1,i,fp) != i)
  1699.     return -1;
  1700.   return 0;
  1701. }
  1702. void cache_rstr(FILE* fp,char* s) {
  1703.   INTsys i;
  1704.   char buff[256+4];
  1705.   linput(fp,buff,256);
  1706.   sscanf(buff,INTsysP,&i);
  1707.   if (i < 0 || i > 32768)    /* error, something nasty happened */
  1708.     i=0;
  1709.   if (i>0) {
  1710.     if ((int) fread(s,1,i,fp) != i) {
  1711.       int fread_cache_failed = 0;
  1712.       assertf(fread_cache_failed);
  1713.     }
  1714.   }
  1715.   *(s+i)='\0';
  1716. }
  1717. char* cache_rstr_addr(FILE* fp) {
  1718.   INTsys i;
  1719.   char* addr = NULL;
  1720.   char buff[256+4];
  1721.   linput(fp,buff,256);
  1722.   sscanf(buff,INTsysP,&i);
  1723.   if (i < 0 || i > 32768)    /* error, something nasty happened */
  1724.     i=0;
  1725.   if (i > 0) {
  1726.     addr = malloct(i + 1);
  1727.     if (addr != NULL) {
  1728.       if ((int) fread(addr,1,i,fp) != i) {
  1729.         int fread_cache_failed = 0;
  1730.         assertf(fread_cache_failed);
  1731.       }
  1732.       *(addr+i)='\0';
  1733.     }
  1734.   }
  1735.   return addr;
  1736. }
  1737. int cache_brstr(char* adr,char* s) {
  1738.   int i;
  1739.   int off;
  1740.   char buff[256+4];
  1741.   off=binput(adr,buff,256);
  1742.   adr+=off;
  1743.   sscanf(buff,"%d",&i);
  1744.   if (i>0)
  1745.     strncpy(s,adr,i);
  1746.   *(s+i)='\0';
  1747.   off+=i;
  1748.   return off;
  1749. }
  1750. int cache_quickbrstr(char* adr,char* s) {
  1751.   int i;
  1752.   int off;
  1753.   char buff[256+4];
  1754.   off=binput(adr,buff,256);
  1755.   adr+=off;
  1756.   sscanf(buff,"%d",&i);
  1757.   if (i>0)
  1758.     strncpy(s,adr,i);
  1759.   *(s+i)='\0';
  1760.   off+=i;
  1761.   return off;
  1762. }
  1763. /* idem, mais en int */
  1764. int cache_brint(char* adr,int* i) {
  1765.   char s[256];
  1766.   int r=cache_brstr(adr,s);
  1767.   if (r!=-1)
  1768.     sscanf(s,"%d",i);
  1769.   return r;
  1770. }
  1771. void cache_rint(FILE* fp,int* i) {
  1772.   char s[256];
  1773.   cache_rstr(fp,s);
  1774.   sscanf(s,"%d",i);
  1775. }
  1776. int cache_wint(FILE* fp,int i) {
  1777.   char s[256];
  1778.   sprintf(s,"%d",(int) i);
  1779.   return cache_wstr(fp,s);
  1780. }
  1781. void cache_rLLint(FILE* fp,LLint* i) {
  1782.   char s[256];
  1783.   cache_rstr(fp,s);
  1784.   sscanf(s,LLintP,i);
  1785. }
  1786. int cache_wLLint(FILE* fp,LLint i) {
  1787.   char s[256];
  1788.   sprintf(s,LLintP,(LLint) i);
  1789.   return cache_wstr(fp,s);
  1790. }
  1791. // -- cache --
  1792.